package com.doform.android.xianggucheng.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.UnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqDeleteMeasureUnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListMeasureUnitBean;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-08-01.
 * GitHub：https://github.com/cxydxpx
 */

public class ListMeasureUnitActivity extends BaseTitleActivity implements OnRefreshListener, OnLoadmoreListener {

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private List<UnitBean.DataBean> mDatas = new ArrayList<>();
    private CommonAdapter<UnitBean.DataBean> mCommonAdapter;

    @Override
    protected int layoutResId() {
        return R.layout.activity_measure_unit;
    }

    @Override
    protected void initView() {
        super.initView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    protected void initListener() {
        super.initListener();

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableHeaderTranslationContent(false);

        mCommonAdapter = new CommonAdapter<UnitBean.DataBean>(this, R.layout.activity_measure_unit_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final UnitBean.DataBean dataBean, int position) {
                TextView tv_code = holder.getView(R.id.tv_code);
                TextView tv_sort = holder.getView(R.id.tv_sort);
                TextView tv_type = holder.getView(R.id.tv_type);
                TextView tv_name = holder.getView(R.id.tv_name);

                tv_code.setText(dataBean.getId());
                tv_sort.setText(dataBean.getCorder());
                tv_name.setText(dataBean.getName());

                /**
                 * {1:公有：系统的不可以修改,2:私有:配送公司自己的可以修改}
                 */

                if (dataBean.getCtype().equals("1")) {
                    tv_type.setText("系统类型");
                    return;
                } else if (dataBean.getCtype().equals("2")) {
                    tv_type.setText("店铺私有");
                } else {
                    tv_type.setText("默认");
                }

                holder.getView(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(dataBean);
                    }
                });


            }
        };

        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                if (mDatas.get(position).getCtype().equals("1")) {
                    TsUtils.showToast("系统计量单位，不可修改");
                    return;
                }
                Intent intent = new Intent(ListMeasureUnitActivity.this, UpdateMeasureUnitActivity.class);
                intent.putExtra(Constans.EXTRA_MEASURE_UNIT, mDatas.get(position));
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    private void showDialog(final UnitBean.DataBean dataBean) {
        new AlertDialog.Builder(this)
                .setMessage("该数据删除后将无法恢复，请确认是否要删除?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(dataBean);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                .show();
    }

    private void deleteItem(UnitBean.DataBean dataBean) {
        HttpManager.instance()
                .deleteMeasureUnit(new ReqDeleteMeasureUnitBean(dataBean.getId(), dataBean.getGuid()))
                .compose(new DialogTransformer<Integer>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        refresh();
                    }
                });
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("计量单位");
    }

    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    /**
     * 首次进入页面
     */
    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(mCurrentPage);
    }

    /**
     * 首次进入页面 获取数据
     *
     * @param mCurrentPage
     */
    private void getDataForService(int mCurrentPage) {

        HttpManager.instance()
                .getMeasureUnit(new ReqListMeasureUnitBean(String.valueOf(mCurrentPage)))
                .compose(new DialogTransformer<UnitBean>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<UnitBean>() {
                               @Override
                               public void onNext(@NonNull UnitBean unitBean) {
                                   parseData(unitBean);
                               }
                           }
                );

    }


    /**
     * 上拉加载 下拉刷新获取数据
     *
     * @param mCurrentPage
     */
    private void getDataForService2(int mCurrentPage) {

        HttpManager.instance()
                .getMeasureUnit(new ReqListMeasureUnitBean(String.valueOf(mCurrentPage)))
                .subscribe(new ErrorHandleSubscriber<UnitBean>() {
                               @Override
                               public void onNext(@NonNull UnitBean unitBean) {
                                   parseData(unitBean);
                               }
                           }
                );

    }

    private void parseData(@NonNull UnitBean unitBean) {

        List<UnitBean.DataBean> list = unitBean.getList();

        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (list.size() == 00 || list == null) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }

        mDatas.addAll(list);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage);
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataForService2(mCurrentPage);
    }

    @OnClick(R.id.btn_add)
    public void click() {
        startActivity(new Intent(this, NewMeasureUnitActivity.class));
    }

}
